package svc

import (
	"fmt"
	"wx_order_server/internal/config"
	"wx_order_server/internal/models"

	"github.com/acmestack/gorm-plus/gplus"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var GlobalDb *gorm.DB
var GlobalRedis *redis.Redis

type ServiceContext struct {
	Config      config.Config
	UserModel   *models.UserModel
	DbEngin     *gorm.DB
	RedisClient *redis.Redis
}

func NewServiceContext(c config.Config) *ServiceContext {
	GlobalDb, _ = gorm.Open(mysql.Open(c.DataSourceName), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "wx_order_", // 表名前缀，`User` 的表名应该是 `t_users`
			SingularTable: true,        // 使用单数表名，启用该选项，此时，`User` 的表名应该是 `t_user`
		},
	})

	redisConfig := redis.RedisConf{
		Host: c.RedisConf.Host,
		Type: c.RedisConf.Type,
		Pass: c.RedisConf.Pass,
		Tls:  c.RedisConf.Tls,
	}

	GlobalRedis = redis.MustNewRedis(redisConfig)

	//更新表结构
	autoErr := GlobalDb.AutoMigrate(
		&models.UserModel{},
	)

	userModel := models.UserModel{}

	if autoErr != nil {
		fmt.Println("AutoMigrate err:", autoErr)
	}
	gplus.Init(GlobalDb)

	return &ServiceContext{
		Config:      c,
		DbEngin:     GlobalDb,
		RedisClient: GlobalRedis,
		UserModel:   &userModel,
	}
}
